package com.jie.deletefile.animtor;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import static android.animation.ValueAnimator.*;

/**
 * Created by 13952137957 on 2016/11/7.
 */

public class SetAnimator {
    private Context context;
    private ImageView imageID;
    private ProgressBar progressID;
    private float maxX;
    private AnimatorSet set;
    private ObjectAnimator animator1;
    private ObjectAnimator animator2;


    /**
     *
     * @param context 上下文，用于获取屏幕宽度
     * @param imageID imageview旋转和平移动画
     * @param progressID 加载进度
     */
    public SetAnimator(Context context, ImageView imageID, ProgressBar progressID) {
        this.context = context;
        this.imageID = imageID;
        this.progressID = progressID;
    }

    /**
     * 方法名：startAnimator
     * 功能:开始动画
     * 参数：无
     * 返回值：void
     */

    public void startAnimator() {
        /**
         * 获取整个屏幕宽度的px
         */
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        maxX = dm.widthPixels;
        set = new AnimatorSet();
        /**
         * 设置旋转动画
         */
        animator1 = ObjectAnimator.ofFloat(imageID, "rotation", 0.0f, 720F);
        //设置动画循环播放
        animator1.setRepeatCount(6000);
        animator1.setRepeatMode(INFINITE);
        //设置平移动画
        animator2 = ObjectAnimator.ofFloat(imageID, "translationX", -80f, maxX);
        //设置动画循环播放
        animator2.setRepeatCount(6000);
        animator2.setRepeatMode(INFINITE);

        //使平移动画和progressbar进度保持同步
        animator2.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {

                //设置progressBar进度
                float currentValue = (float) animation.getAnimatedValue();
                progressID.setProgress((int) (100 * currentValue / maxX + 5));
            }
        });

        //设置动画集合
        set.playTogether(animator1, animator2);
        //设置动画时间
        set.setDuration(6000);
        //开始动画集合
        set.start();
    }


    /**
     * 方法名：stopAnimator
     * 功能:停止动画
     * 参数：无
     * 返回值：void
     */
    public void stopAnimator() {
        //kill掉动画集合
        set.cancel();
        imageID.setVisibility(View.GONE);
        progressID.setVisibility(View.GONE);
    }
}
